package com.shteo.crmd.web.controller;

import com.auth0.jwt.JWTSigner;
import com.shteo.crmd.common.source.AKResult;
import com.shteo.crmd.model.goods.Goods;
import com.shteo.crmd.model.order.Order;
import com.shteo.crmd.web.exception.APIException;
import com.shteo.crmd.web.feign.IFCGoods;
import com.shteo.crmd.web.feign.IFCOrder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Akuma on 16/9/28.
 */
@Api(value = "测试接口",description="用于测试各种接口",tags = "/test")
@RestController
@RequestMapping("/test")
public class TestController extends BaseController{


    private Logger logger = Logger.getLogger(TestController.class);

    @Value("${jwt.issuer}")
    private String issuer;

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.exp}")
    private Long exp;

    @Autowired
    private IFCGoods fcGoods;

    @Autowired
    private IFCOrder fcOrder;

    //模拟用户服务
    private Map<String,Map<String,String>> userService = new HashMap<>();


    {
        //初始化数据
        Map<String,String> ui = new HashMap<>();
        ui.put("userId","10000");
        ui.put("account","admin");
        ui.put("password","admin");
        ui.put("userName","Akuma");
        userService.put("admin",ui);
    }


    @ApiOperation("用户登录")
    @PostMapping("/login")
    public String login(
            @ApiParam("账号")@RequestParam("account")String account,
            @ApiParam("密码")@RequestParam("password")String password){
        logger.info(getRequest().getSession().getId());
        //模拟登录
        Map<String,String> userInfo = userService.get(account);
        if (userInfo!=null&&userInfo.get("password").equals(password)){
            //登陆成功
            //生成调用凭证
            long iat = System.currentTimeMillis() / 1000L; // issued at claim
            exp += iat; // expires claim. In this case the token expires in 60 seconds
            JWTSigner signer = new JWTSigner(secret);
            HashMap<String, Object> claims = new HashMap<String, Object>();
            claims.put("iss", issuer);
            claims.put("exp", exp);
            claims.put("iat", iat);
            claims.put("aud",userInfo.get("userId"));//接受者userId
            claims.put("un",userInfo.get("userName"));//用户名称

            String jwt = signer.sign(claims);
            logger.info(userInfo.get("userId")+":"+jwt);
            return AKResult.builder().ok().errMsg("登陆成功").data(jwt).build();
        }
        return AKResult.builder().fail().errMsg("用户名或密码错误").build();
    }



    @ApiOperation("添加商品")
    @PostMapping("/addGoods")
    public String addGoods(@ApiParam("商品")@RequestBody Goods goods){
        AKResult result = fcGoods.add(goods);
        return result.build();
    }


    @ApiOperation("获取所有商品")
    @GetMapping("/getGoods")
    public String getGoods(){
        List<Goods> goodsList = fcGoods.getAllGoods();
        return Optional.ofNullable(goodsList).map(list->AKResult.builder().ok().errMsg("查询成功").data(goodsList).build())
                .orElseThrow(()->new APIException("Goods List Not Found"));
    }


    @ApiOperation("获取商品明细")
    @GetMapping("/getGoods/{goodsId}")
    public String getGoods(@ApiParam("商品ID")@PathVariable("goodsId")Long goodsId){
        Goods goods = fcGoods.getGoodsById(goodsId);
        return Optional.ofNullable(goods)
                .map(g->AKResult.builder().ok().errMsg("查询成功").data(g).build())
                .orElseThrow(()->new APIException("Goods Not Found"));
    }

    @ApiOperation("删除商品")
    @DeleteMapping("/delGoods/{goodsId}")
    public String delGoods(@ApiParam("商品ID")@PathVariable("goodsId")Long goodsId){
        return fcGoods.delGoodsById(goodsId).build();
    }

    @ApiOperation("更新商品")
    @PutMapping("/updateGoods")
    public String updateGoods(@ApiParam("商品")@RequestBody Goods goods){
        return fcGoods.updateGoodsById(goods).build();
    }


    @ApiOperation("添加订单")
    @PostMapping("/addOrder")
    public String addOrder(@ApiParam("订单")@RequestBody Order order){

        //查询商品价格
        Goods goods = fcGoods.getGoodsById(order.getGoodsId());
        if (goods!=null){
            if (goods.getStock()>=order.getQuantity()){
                BigDecimal totalMoney = goods.getPrice().multiply(new BigDecimal(order.getQuantity()));
                //设置订单总金额
                order.setTotalMoney(totalMoney);
                AKResult result = fcOrder.add(order);
                if (result.success()){
                    //扣除库存
                    AKResult re = fcGoods.subStock(goods.getId(),order.getQuantity());

                }
                return AKResult.builder().ok().errMsg("下单成功").build();
            }else{
                return AKResult.builder().fail().errMsg("商品库存不足").build();
            }
        }else{
            return AKResult.builder().fail().errMsg("找不到商品信息.").build();
        }
    }

}
